package com.example.concurrentprogramming8016.disruptor.produceconsumer.singleproduce;

import com.example.concurrentprogramming8016.disruptor.produceconsumer.singleproduceconsumer.OrderEvent;
import com.example.concurrentprogramming8016.disruptor.produceconsumer.singleproduceconsumer.OrderEventFactory;
import com.example.concurrentprogramming8016.disruptor.produceconsumer.singleproduceconsumer.OrderEventProducer;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executors;

/**
 * @author liyanhao
 * @Date 2023-01-08 14:32
 */
public class Test {
    public static void main(String[] args) {
        //创建disruptor
        Disruptor<OrderEvent> disruptor = new Disruptor<>(
                new OrderEventFactory(),
                1024 * 1024,
                Executors.defaultThreadFactory(),
                ProducerType.MULTI,//多生产者
                new YieldingWaitStrategy()//等待策略
        );
        //设置消费者用于处理
//        disruptor.handleEventsWith(new OrderEventHandler());
        //设置多消费者 消费会被重复消费
      /*  disruptor.handleEventsWith(new OrderEventHandler(),
                new OrderEventHandler());*/
        //设置多消费者 消费者要实现workHandler接口 一个消息只会被一个消费者消费
        disruptor.handleEventsWith(new OrderEventHandler(), new OrderEventHandler());
        //启动disruptor
        disruptor.start();
        //创建ringbuffer
        RingBuffer<OrderEvent> ringBuffer = disruptor.getRingBuffer();
        new Thread(() -> {
            //创建生产者
            OrderEventProducer orderEventProducer = new OrderEventProducer(ringBuffer);
            //发送消息
            for (int i = 0; i < 100; i++) {
                orderEventProducer.onData(i, "liyanhao:" + i);
            }
        }, "prodcuce-1").start();
        new Thread(() -> {
            //创建生产者
            OrderEventProducer orderEventProducer = new OrderEventProducer(ringBuffer);
            //发送消息
            for (int i = 0; i < 100; i++) {
                orderEventProducer.onData(i, "liyanhao2:" + i);
            }
        }, "prodcuce-2").start();

        disruptor.shutdown();

    }
}
